<template>
  <div class="self_background">
        <StoreHeaderCat />

    <div class="bottom_line"></div>

    <div class="wrap clearfix">
      <div class="s1">
        <div class="sr-layout-block fl">
          <div class="sr-txt-title">
            <h2 class="sr-txt-h2">{{ L["取得联系"] }}</h2>
          </div>

            <div class="item">
              <img src="/contactUsPng3.png" />
              <p class="t1">{{ L["客服邮箱"] }}</p>
              <p>{{email}}</p>
            </div>

            <div class="item">
              <img src="/contactUsPng2.png" />
              <p class="t1">{{ L["联系人电话"] }}</p>
              <p>{{phone}}</p>
            </div>

            <div class="item">
              <img src="/contactUsPng1.png" />
              <p class="t1">{{ L["公司地址"] }}</p>
              <p>{{address}}</p>
            </div>

        </div>
        <div class="sr-layout-block fr" v-if="ifMapReload">
          <div class="sr-txt-title">
            <h2 class="sr-txt-h2">{{ L["将您的消息发送到此供应商"] }}</h2>
          </div>
          <el-form
            ref="ruleFormRef"
            :model="form"
            label-position="top"
            label-width="120px"
            :rules="rules"
            size="large"
            status-icon
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label= "L['姓名']" prop="name">
                  <el-input
                    v-model="form.name"
                    :placeholder="L['请输入姓名']"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="L['邮箱']" prop="email">
                  <el-input
                    v-model="form.email"
                    :placeholder="L['请输入邮箱']"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="L['电话代码']" prop="phoneCode">
                  <el-select v-model="form.phoneCode" :placeholder="L['选择国家/地区']" filterable clearable allow-create  style="width: 100%">
                    <el-option
                            v-for="item in countryPhone"
                            :key="item.value"
                            :label="item.label"
                            :value="(item.label+'/'+item.value)">
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="L['电话']" prop="phone">
                  <el-input
                    v-model="form.phone"
                    :placeholder="L['请输入电话']"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="L['公司名称']" prop="company">
                  <el-input
                    v-model="form.company"
                    :placeholder="L['请输入公司名称']"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="L['留言']" prop="message">
                  <el-input
                    v-model="form.message"
                    type="textarea"
                    :rows="8"
                    :placeholder="L['请输入留言']"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitForm(ruleFormRef)"
                    style="flex: 48% 0 0; margin: 10px 1% 0"
                    class="self-btn"
                    :loading="loading"
                  >{{ L["发送"]}}</el-button
                  >
                  <el-button
                    @click="closeModal(ruleFormRef)"
                    style="flex: 48% 0 0; margin: 10px 1% 0"
                    class="cancel-btn"
                    >{{ L["重置"]}}</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div v-if="ifMapReload && center.data.lat != ''">
        <GoogleMap
          api-key="AIzaSyAvTVnnDLfxdaK2i-f0pRMJOrdwZvxUBjU"
          style="width: 100%; height: 500px"
          :center="center.data"
          :zoom="5"
          >
            <Marker :options="{ position: center.data }" />
          </GoogleMap>

      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ElSelect,
  ElOption,
  ElMessage,
  ElForm,
  ElFormItem,
  ElButton,
  ElInput,
  ElRow,
  ElCol,
} from "element-plus";
import { useFiltersStore } from "@/store/filter.js";
import { GoogleMap, Marker } from 'vue3-google-map'
import { getCurLanguage } from '@/composables/common.js';

const L = getCurLanguage();
const center = reactive({data:{ lat: 0, lng: 0 }})
const address = ref()
const email = ref()
const phone = ref()
const route = useRoute();
const router = useRouter();

const vid = calcUrlShopId(route.path);
const ruleFormRef = ref(null);
const ifMapReload = ref(false)
const loading = ref(false);
const form = reactive({
  name: "",
  email: "",
  phoneCode: "",
  phone: "",
  company: "",
  message: "",
});
const filtersStore = useFiltersStore();
const countryPhone = ref([]);

useHead({
    title: 'Store Contact Us',
    meta: [
      {
        name: "description",
        content:'Store Contact Us',
      },
      {
        name: "keywords",
        content: 'Store Contact Us',
      },
    ],
  });

if(filtersStore.getMemberInfo.memberEmail){
  form.email = filtersStore.getMemberInfo.memberEmail
}
if(filtersStore.getMemberInfo.memberNickName || filtersStore.getMemberInfo.memberName){
  form.name = filtersStore.getMemberInfo.memberNickName || filtersStore.getMemberInfo.memberName
}

const checkEmailFun = (rule, value, callback) => {
  if (checkEmail(value) !== true) {
    callback(new Error(checkEmail(value)));
  }
  callback();
};

const checkPhoneFun = (rule, value, callback) => {
  if (checkPhone(value) !== true) {
    callback(new Error(checkPhone(value)));
  }
  callback();
};

const closeModal = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  loading.value = false;
};

const rules = reactive({
  name: [{ required: true, message: L["请输入姓名"], trigger: "blur" }],
  email: [
    { required: true, message: L["请输入邮箱"], trigger: "blur" },
    { validator: checkEmailFun, trigger: "blur" },
  ],
  phoneCode: [
    {
      required: true,
      message: L["请选择国家/地区"],
      trigger: ['blur','change'],
    },
  ],
  // phone: [
  //   { required: true, message: L["请输入电话"], trigger: "blur" },
  //   // { validator: checkPhoneFun, trigger: "blur" },
  // ],
  company: [
    {
      required: true,
      message: L["请输入公司名称"],
      trigger: "blur",
    },
  ],
  message: [
    {
      required: true,
      message: L["请输入留言"],
      trigger: "blur",
    },
  ],
});


//提交按钮
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {

      let url = "";
      if (!filtersStore.getLoginFlag) {
        url = apiUrl + "v3/member/front/enquiry/add";
      } else {
        url = apiUrl + "v3/member/front/enquiry/save";
      }

      let d = {}
      d = Object.assign({},form)

      d.pageUrl = window.location.href;
      d.itemId = vid ? vid : "";
      d.itemType = vid ? "SHOP" : "MALL";
      let a = d.phoneCode

      d.phoneCode = a.split('/')[1] ?  a.split('/')[1] : ''
      d.country = a.split('/')[0]

      loading.value = true;
      post(url, d).then((res) => {
        if (res.state == 200) {
          ElMessage.success(res.msg);
          loading.value = false;
          closeModal(formEl);
        } else {
          ElMessage.error(res.msg);
        }
      }).finally(()=>{
        loading.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

//获取经纬度
const getMapInfo = () => {
  get('v3/seller/front/store/detail?storeId='+ vid).then(res=>{
    address.value = res.data.address
    email.value = res.data.email
    phone.value = res.data.servicePhone
    center.data.lat = Number(res.data.storeMapInfo)
    center.data.lng = Number(res.data.storeMapInfoW)
    ifMapReload.value =true
  })

}

//获取国家电话code
const getPhoneCode = () => {
  get('/v3/member/front/enquiry/phoneCode').then(res=>{
    countryPhone.value = res.data;
  })
}

getMapInfo()
  getPhoneCode()

onMounted(() => {

  setTimeout(() => {
    sldStatEvent({ behaviorType: 'spv', storeId: vid ,pageUrl: defaultUrl + router.currentRoute.value.path, referrerPageUrl: apiUrl });
    }, 3000)
})

</script>

<style lang="scss" scoped>
@import "@/assets/style/store/contac-about.scss";
@import "@/assets/style/contact.scss";
</style>
